<template>
  <div id="marketing">
    <h3 class="main-title">我的活动</h3>
    <!-- <div class="search-extend mr12">
      活动来源：
      <el-select v-model="sourceValue" placeholder="请选择">
        <el-option
          v-for="item in sourceOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      活动状态:
      <el-select v-model="statusValue" placeholder="请选择">
        <el-option
          v-for="item in statusOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      是否下发：
      <el-select v-model="issuedValue" placeholder="请选择">
        <el-option
          v-for="item in issuedOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
    </div> -->
    <div class="search-box">
      <el-input placeholder="输入标题、活动编码" v-model="searchForm.search" @keyup.enter.native="submitSearch">
        <el-button slot="append" @click="submitSearch">搜索</el-button>
      </el-input>
    </div>
    <div class="campaign-control mr12">
      <el-button @click="handleNewActivity">新建活动</el-button>
      <!-- <el-button @click="multiDelete" v-if="multiDel">批量删除</el-button>
      <el-button v-else disabled>批量删除</el-button> -->
      <el-button v-show="hasReportAuthority" @click="gotoNewReport" style="float: right;">报表</el-button>
    </div>
    <div class="result-box">
      <el-table
        v-loading="tbLoading"
        border
        element-loading-text="拼命加载中"
        ref="multipleTable"
        :data="tableData.list"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="活动编码">
          <template slot-scope="props">{{ props.row.id }}</template>
        </el-table-column>
        <el-table-column label="活动标题">
          <template slot-scope="props">{{ props.row.name }}</template>
        </el-table-column>
        <!-- <el-table-column width="70"></el-table-column> -->
        <el-table-column label="活动时间" width="220">
          <template slot-scope="props">{{ $date.format(props.row.startTime*1000, 'YYYY-MM-DD') }}到{{ $date.format(props.row.endTime*1000, 'YYYY-MM-DD') }}</template>
        </el-table-column>
        <el-table-column label="活动来源">
          <template slot-scope="props">{{ props.row.source }}</template>
        </el-table-column>
        <el-table-column label="活动状态">
          <template slot-scope="props">{{ props.row.statusName }}</template>
        </el-table-column>
        <!-- <el-table-column label="是否下发">
          <template slot-scope="props">{{ props.row.issue }}</template>
        </el-table-column> -->
        <el-table-column label="操作">
          <template slot-scope="props">
            <el-dropdown @command="(command) => handleCommand(command, props)" trigger="hover">
              <span class="el-dropdown-link">
                -操作-<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="details">
                  详情
                </el-dropdown-item>
                <el-dropdown-item command="issued" v-show="props.row.canPush">推送销售代表</el-dropdown-item>
                <el-dropdown-item command="issued2" v-show="props.row.canIssued">下发子公司</el-dropdown-item>
                <!-- <el-dropdown-item command="issued2">下发分公司</el-dropdown-item>-->
                <el-dropdown-item command="report">报表</el-dropdown-item>
                <!-- <el-dropdown-item command="edit" v-show="props.row.canEdit">编辑</el-dropdown-item> -->
                <el-dropdown-item command="delete" v-show="props.row.canDel">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        :current-page.sync="searchForm.page"
        :page-size.sync="searchForm.size"
        layout="sizes, total, prev, pager, next, jumper"
        :total.sync="totalData"
        :page-sizes="[10, 30, 50, 100]"
        @current-change="initPageData()"
        @size-change="handleSizeChange">
      </el-pagination>
    </div>

    <div class="new-wrap">
      <el-dialog :title="newTitle" width="30%" :visible.sync="dialogFormVisible">
        <el-form :model="newForm">
          <el-form-item label="* 活动名称">
            <el-input v-model="newForm.name" auto-complete="off" placeholder="请输入活动名称"></el-input>
          </el-form-item>
          <el-form-item label="* 活动描述">
            <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入活动描述" v-model="newForm.desc"></el-input>
          </el-form-item>
          <el-form-item label="* 活动时间">
            <el-date-picker
              v-model="date"
              type="daterange"
              @change="dateChange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="* 卡券库存">
            <el-input v-model="newForm.cardNum" auto-complete="off" placeholder="请输入卡券库存"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelNew">取 消</el-button>
          <el-button type="primary" @click="submitNew">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 下发到销售代表 -->
    <el-dialog title="下发" :visible.sync="dialog" custom-class="dialog_issue">
      <saler-list :showAuth="false" :showSync="false" :showCheckedAll="true" :selected="selectedUser" @onSelectUser="handleSelectUser" @checkedAll="handleCheckedAll"></saler-list>
      <div class="selected_user">
        <div class="title">已选择{{selectedUser.length}}个联系人</div>
        <div v-for="item, n in selectedUser"  class="user_item">
          <!--<img class="avatar" :src="item.avatar||''" alt="">-->
          {{item.username}}
          <i class="el-icon-close" @click="handleUnSelectUser(n)"></i>
        </div>
        <div class="btns" style="margin-top: 30px;">
          <el-button size="mini" v-show="selectedUser.length" @click="handleClearUser">清空</el-button>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog = false">取 消</el-button>
        <el-button type="primary" @click="handleIssueSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 推送到分公司 -->
    <el-dialog title="推送分公司" :visible.sync="dialog2" custom-class="dialog_issue">
      <saler-list :showAuth="false" :showSync="false" :showUser="false" @onSelectGroup="handleSelectGroup">
      </saler-list>
      <div class="selected_user">
        <div class="title">已选择{{selectedGroup.length}}个联系人</div>
        <div v-for="item, n in selectedGroup"  class="user_item">
          <span>{{item.name}}</span>
          <i class="el-icon-close" @click="handleUnSelectGroup(n)"></i>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog2 = false">取 消</el-button>
        <el-button type="primary" @click="handleIssueSubmit2">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 下发类型选择 -->
    <el-dialog title="请选择下发类型" :visible.sync="dialog3">
      <el-button @click="dialog = true ; dialog3 = false">按销售代表推送</el-button>
      <el-button type="primary" @click="dialog2 = true; dialog3 = false">按分公司推送</el-button>
    </el-dialog>
    <!-- 下发到子公司 -->
    <el-dialog title="下发到子公司" :visible.sync="dialog4" custom-class="dialog_issue">
      <saler-list :showAuth="false" :showSync="false" :showUser="false" @onSelectGroup="handleSelectChildGroup">
      </saler-list>
      <div class="selected_user">
        <div class="title">已选择{{selectedChildGroup.length}}个联系人</div>
        <div v-for="item, n in selectedChildGroup"  class="user_item">
          <span>{{item.name}}</span>
          <i class="el-icon-close" @click="handleUnSelectChildGroup(n)"></i>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog4 = false">取 消</el-button>
        <el-button type="primary" @click="handleIssueSubmit3">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {mapMutations, mapState, mapActions} from 'vuex'
import salerList from '@/components/common/sysManage/salerList'
import {getBranchCompanyCollect} from "@/service/getData";
export default {
  components: {salerList},
  data () {
    return {
      searchForm: {
        search: '',
        page: 1,
        size: 10
      },
      totalData: 0,
      tbLoading: false,
      multiDel:false,
      dialogFormVisible: false,
      date: [],
      newTitle: '新建活动',
      newForm: {
        name: '',
        dateVal: '',
        cardNum: null,
        desc: ''
      },
      sourceValue: '',
      statusValue: '',
      issuedValue: '',
      sourceOptions: [{
        value: '0',
        label: '不限'
      },{
        value: '1',
        label: '总部下发的'
      },{
        value: '2',
        label: '我创建的'
      }],
      statusOptions: [{
        value: '0',
        label: '不限'
      },{
        value: '1',
        label: '未开始'
      },{
        value: '2',
        label: '进行中'
      },{
        value: '3',
        label: '已结束'
      }],
      issuedOptions: [{
        value: '0',
        label: '不限'
      },{
        value: '1',
        label: '未下发'
      },{
        value: '2',
        label: '已下发'
      }],
      tableData: [],
      multipleSelection: [],
      selectedUser: [],
      selectedGroup: [],
      selectedChildGroup: [],
      dialog: false,
      dialog2: false,
      dialog3: false,
      dialog4: false,
      newActivityId: '',
      activityType: 1,
      hasReportAuthority: false
    }
  },
  computed: {
    ...mapMutations(['GET_CAMPAIGNLIST', 'SEARCH_CAMPAIGNLIST']),
    ...mapState({
      campaignList: state => state.campaignList.campaignList
    }),
    userSelected() {
      return this.selectedUser
    }
  },
  mounted () {
    this.initPageData()
  },
  methods: {
    ...mapActions([ 'getCampignData', 'newCampaignData', 'issueCampaign', 'issueCampaign2', 'issueCampaign3', 'setPostData', 'savePostData', 'delCampaignData' ]),
    initPageData () {
      this.getTableData()
      this.checkReportAuthority()
    },
    gotoNewReport() {
      this.$router.push({
        name: 'CampaignNewReport'
      })
    },
    submitSearch () {
      this.tbLoading = true
      if (this.searchForm.search) {
        this.getCampignData({ ...this.searchForm }).then((res) => {
          if(res.data.code === 1){
            this.tableData = res.data.data
            this.tbLoading = false
          }
        })
      } else {
        this.getTableData()
      }

    },
    checkReportAuthority() {
      const t1 = new Date()
      const t2 = new Date()
      t1.setHours(0, 0, 0)
      t2.setHours(23, 59, 59)
      getBranchCompanyCollect({
        startTime: Math.floor(t1.getTime() / 1000),
        endTime: Math.floor(t2.getTime() / 1000),
        departmentId: '',
        search: '',
        page: 1,
        size: 10
      }).then(() => {
        this.hasReportAuthority = true
      }).catch(() => {
        this.hasReportAuthority = false
      })
    },
    async getTableData () {
      this.tbLoading = true
      let _this = this
      await this.getCampignData({ ...this.searchForm }).then((res) =>{
        if(res.data.code === 1){
          _this.totalData = res.data.data.page.total
          _this.tableData = res.data.data
          _this.tbLoading = false
        }
      })
      return this.tableData
    },
    handleSizeChange (size) {
      this.searchForm.size = size
      this.submitSearch()
    },
    handleNewActivity () {
      this.activityType = 1
      this.dialogFormVisible = true
    },
    multiDelete () {
      console.log('批量')
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      if(val.length > 0){
        this.multiDel = true
      }else{
        this.multiDel = false
      }
    },
    dateChange(val) {
      this.newForm.dateVal = val
    },
    submitNew () {
      if(!this.newForm.name){
        this.$message({
          type: 'info',
          message: '请填写活动标题！'
        })
        return;
      }else if(!this.newForm.desc){
        this.$message({
          type: 'info',
          message: '请填写活动描述！'
        })
        return;
      }
      if(this.activityType === 1){
        if(!this.newForm.dateVal){
          this.$message({
            type: 'info',
            message: '请选择活动时间范围！'
          })
          return;
        }
      }else if(this.activityType === 2){
        if(!this.date){
          this.$message({
            type: 'info',
            message: '请选择活动时间范围！'
          })
          return;
        }
      }
      if(isNaN(this.newForm.cardNum)){
        this.$message({
          type: 'info',
          message: '卡券库存只能填数字！'
        })
        return;
      }
      if(!this.newForm.cardNum){
        this.$message({
          type: 'info',
          message: '请填写卡券库存！'
        })
        return;
      }
      // let startTime,endTime
      // if(this.newActivityId){ //编辑
      //   startTime = new Date(this.date[0]),
      //   endTime = new Date(this.date[1])
      // }else{ //新建
      //   startTime = this.newForm.dateVal.replace('至',',').split(',')[0],
      //   endTime = this.newForm.dateVal.replace('至',',').split(',')[1]
      // }
      console.log(this.newForm.dateVal)
      this.savePostData({
        activityId: this.newActivityId,
        name: this.newForm.name,
        desc: this.newForm.desc,
        cardNum: this.newForm.cardNum,
        startTime: new Date(this.date[0]).getTime()/1000, //解决时间8点开始
        endTime: new Date(this.date[1]).getTime()/1000
      }).then((res)=> {
        if(res.data.code ===1){
          this.$message.success('创建成功！');
          this.getTableData().then((data) => {
            let _id = data.list[0].id
            this.$router.push({name: 'NewCampaign', params: {id: _id}})
          })
          this.dialogFormVisible = false
          //this.$router.push({name: 'NewCampaign', params: {id: props.row.id}})
        }else{
          this.$message.error(res.msgZ);
        }
      })
      this.date = ''
      this.newForm = {
        name: '',
        dateVal: '',
        desc: ''
      }
    },
    cancelNew(){
      this.dialogFormVisible = false
      this.newTitle = ''
      this.date = ''
      this.newForm = {
        name: '',
        dateVal: '',
        desc: ''
      }
    },
    handleCommand (command, props) {
      if (command === 'details') {
        this.$router.push({name: 'CampaignDetail', params: {id: props.row.id}})
      } else if (command === 'issued') {
        this.curActivity = props.row
        this.dialog3 = true
      } else if (command === 'issued2') { //下发给子公司
        // TODO
        this.curActivity = props.row
        this.dialog4 = true
      } else if (command === 'report') {
        this.$router.push({name: 'CampaignReport', params: {id: props.row.id}})
      }else if (command === 'edit') {
        this.newTitle = '编辑活动'
        this.newForm.name = this.tableData.list[props.$index].name
        this.newForm.desc = this.tableData.list[props.$index].desc
        let st = this.tableData.list[props.$index].startTime*1000,
            et = this.tableData.list[props.$index].endTime*1000
        this.date = [new Date(st),new Date(et)]
        this.newActivityId = props.row.id
        this.activityType = 2
        //this.newForm.dateVal = [new Date(st),new Date(et)]
        this.dialogFormVisible = true
      }else if (command === 'delete') {
        this.$confirm('删除后，相关报表信息也会同步。确定删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: false
        }).then(() =>{
          let delArr = []
          delArr.push(props.row.id)
          this.delCampaignData(delArr).then((res) =>{
            if(res.data.code === 1){
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            this.getTableData()
            }else{
              this.$message({
                type: 'info',
                message: res.data.msgZ
              })
            }
          })
        }).catch(() =>{
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },

    // 全选销代
    handleCheckedAll(value) {
      this.selectedUser = value
    },

    // 清空销代
    handleClearUser() {
      this.selectedUser = []
    },

    // 选择下发用户
    handleSelectUser (user) {
      if (this.selectedUser.findIndex(item => item.userId === user.userId) === -1) {
        this.selectedUser.push(user)
      }
    },
    // 选择下发公司
    handleSelectGroup (group) {
      if (this.selectedGroup.findIndex(item => item.id === group.id) === -1) {
        this.selectedGroup.push(group)
      }
    },
    handleUnSelectGroup (n) {
      this.selectedGroup.splice(n, 1)
    },
    handleSelectChildGroup (group) {
      if (this.selectedChildGroup.findIndex(item => item.id === group.id) === -1) {
        this.selectedChildGroup.push(group)
      }
    },
    handleUnSelectChildGroup (n) {
      this.selectedChildGroup.splice(n, 1)
    },
    // 删除下发用户
    handleUnSelectUser (n) {
      this.selectedUser.splice(n,1)
    },
    // 确认推送销售代表
    async handleIssueSubmit () {
      const activityId = this.curActivity.id
      const userIds = this.selectedUser.map(item => item.userId)
      const res = await this.issueCampaign({activityId, userIds})
      if (res.data.code === 1) {
        this.$message.success('推送成功')
        this.dialog = false
        this.selectedUser = []
      }
    },
    // 确认推送分公司
    async handleIssueSubmit2 () {
      const activityId = this.curActivity.id
      const departmentIds = this.selectedGroup.map(item => item.id)
      const res = await this.issueCampaign2({activityId, departmentIds})
      if (res.data.code === 1) {
        this.$message.success('推送成功')
        this.dialog2 = false
        this.selectedGroup = []
      }
    },
    // 确认下发子公司
    async handleIssueSubmit3 () {
      const activityId = this.curActivity.id
      const departmentIds = this.selectedChildGroup.map(item => item.id)
      const res = await this.issueCampaign3({activityId, departmentIds})
      if (res.data.code === 1) {
        this.$message.success('下发成功')
        this.dialog4 = false
        this.selectedChildGroup = []
      }
    }
  }
}
</script>

<style lang="scss">
  #marketing{
    .mr12{margin: 12px 0;}
    .main-title{
      font-size: 16px;
      font-weight: normal;
      border-bottom: 1px solid #ccc;
      padding-bottom: 12px;
      margin-bottom: 12px;
    }
    .search-box{
      width: 30%;
    }
    .search-extend{
      .el-select{margin-right: 30px;}
    }
    .el-table th, .el-table td{
      text-align: center;
    }
    .el-dropdown{
      font-size: 12px;
      padding: 1px 8px;
      border-radius: 3px;
      border: 1px solid #ccc;
      cursor: pointer;
      .el-icon--right{
        margin-left: 15px;
      }
    }
    .dialog_issue{
      &{width:1000px}
      .el-dialog__body{max-height:600px;overflow:auto}
      .saler_list{
        float:left;
        width:700px;
        .group_list{
          .el-input{
            width: 100%;
          }
        }
      }
      .selected_user{
        &{margin-left:710px;padding:10px;min-height:443px;border:1px solid #D1DBE5;}
        .title{margin-bottom:10px;}
        .user_item{margin-bottom:10px;}
        .user_item img{width:26px;height:26px;}
        .el-icon-close{float:right;font-size:12px;cursor:pointer;}
        span{display: inline-block;max-width: 202px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;}
      }
    }
    .el-form-item__content{
      display: inline-block;
      width: 78%;
    }
    .el-range-editor{
      width: 100%;
    }
    .el-dropdown-menu__item a{
      text-decoration: none;
      color: #48576a;
      display: block;
    }
  }
</style>

